import sys
import os
import json
import re

package_name = input('请输入表名：')
# print(type(package_name))
# f = open("target.txt")
# print(type(f))
# data=f.read()
# print(type(data))
# print(f.read())
# arrays = f.readlines() 
# print(type(arrays))
# for array in arrays:
# 	print(array)
# json_str=json.dumps(data)
# print(type(json_str))
# print(json_str)
# json_dict = json.loads(json_str)
# print(type(json_dict)) # str
# print(json_dict['Model'])
java_name = ''
temp_package_name = package_name
main_content = []

main_content.append('\n')

def changeUpperForV(s):
	if s.isupper():
		return s.lower()
	elif (s[0].isupper()):
		return s[0].lower() + s[1:]

def changeUpperForK(s):
	if s.isupper():
		return s[0].upper() + s[1:].lower()
	return s

def getandsetter(l):
	# print(l)
	# print(l[5])
	lines = '\n'+'public void set' + l[6][0].upper() + l[6][1:-1] + '(' + l[5] + ' ' + l[6][:-1] + ') {\n'+'    this.'+l[6][:-1]+'=' + l[6][:-1] + ';\n'+ '}\n'
	lines = lines + 'public ' +l[5]+' get' + l[6][0].upper() + l[6][1:-1] +'(){\n' + '    return ' + ' this.' + l[6] + '\n}' 
	return lines
	# line = '\n public vid set{0}({1} {2}){' + \
	# 		+ 'this.{3}={4};\n'+'}\n' + \
	# 		+ '\n public {5} get{6}()：{\n' + \
	# 		+ '    return this.{7};\n}'.format(l[6][0].upper(),l[5],l[6],l[6],l[6],l)
# 1.先判断包名是否包含下滑线，如果包含，去掉下滑线，并拼接字母小写为包名
if (package_name.find('_') != -1):
	package_name = ''.join(value.lower() for value in package_name.split('_')) 
else:
	package_name = package_name.lower()

def makeDicFile(s,t):
	dic_contents = []
	dic_contents.append('public class ' + s + ' {\n')
	# dic_contents.append('    public static void main(String[] args) {\n')
	# dic_contents.append('        System.out.println("Hello World!");\n')
	# dic_contents.append('    }\n')
	# print('---->', type(t)) # <class 'dict'>
	for k,v in t.items():
		if isinstance(v, int):
			dic_contents.append('    private int ' + changeUpperForV(k) + ';\n')
		elif isinstance(v, str):
			dic_contents.append('    private String ' + changeUpperForV(k) + ';\n')
	# for item in dic_contents:
		# if item.find(s) >= 0:
			# continue
		# else:
			# lists = item.split(' ')

			# print(lists) # ['', '', '', '', 'private', 'String', 'fNumber;\n']
			# lines = ''
			# lines = '\n'+'public void set' + lists[6].replace("\n","")[0].upper() + lists[6].replace("\n","")[1:-1] + '(' + lists[5] + ' ' + lists[6].replace("\n","")[:-1] + ') {\n'+'    this.'+lists[6].replace("\n","")[:-1]+'=' + lists[6].replace("\n","")[:-1] + ';\n'+ '}\n'
			# lines = lines + 'public ' +lists[5]+' get' + lists[6].replace("\n","")[0].upper() + lists[6].replace("\n","")[1:-1] +'(){\n' + '    return ' + ' this.' + lists[6].replace("\n","")[:-1] + '\n}' 
			# dic_contents.append(lines)
	dic_contents.append('}')
	with open(package_name + '/' + s +'.java','w') as f:
		f.writelines(dic_contents)

with open('target.json', 'r', encoding='utf-8') as f:
	ret_dict = json.load(f)
	# print(type(ret_dict)) #<class 'dict'>
	# print(ret_dict)
	# if isinstance(ret_dict['Model'],dict):
	# 	print('我是dict')
	# # folder = os.path.exits(package_name)
	# if not folder:
	
	

	# print(package_name)
	# 2.判断包名是否存在如果不存在，转3，否则转4
	if not os.path.exists(package_name):
		os.makedirs(package_name)
		print('创建目录：', package_name, "完成")
	# 在该目录下创建java名称
	if (temp_package_name.find('_') != -1):
		java_name = ''.join(value[:1].upper() + value[1:].lower() for value in temp_package_name.split('_'))
	else:
		java_name = temp_package_name[:1].upper() + temp_package_name[1:].lower()
	print('java_name:',java_name)
     
	main_content.append('public class ' + java_name + ' {\n')

    # 
	for k,v in ret_dict.items():
		# print(k,v,type(v))
		# split_upper(k)
		# 如果v是整数
		if isinstance(v, int):
			main_content.append('    private int ' + changeUpperForV(k) + ';\n')
		# 如果v是str，且为true或false
		elif (isinstance(v,str) and (v == 'true') or (v == 'false')):
			main_content.append('    private boolean ' + changeUpperForV(k) + ';\n')
		# 如果v是str
		elif (isinstance(v,str)):
			main_content.append('    private String ' + changeUpperForV(k)+ ';\n')
		# 如果v是dict
		elif (isinstance(v,dict)):
			main_content.append('    private ' + changeUpperForK(k) + ' ' + changeUpperForV(k)+ ';\n')
			# 生成java文件到package_name下
			# print(type(ret_dict[k]))
			makeDicFile(changeUpperForK(k),v)
		# 如果是数组
		elif (isinstance(v,list)):
			main_content.append('    private List<' + k + '> ' + changeUpperForV(k)+ ';\n')
			print(type(v[0]))
			makeDicFile(changeUpperForK(k), v[0])
	# for item in main_content:
	# 	if (item.find(java_name) >= 0 or item.find('\n')>= 0):
	# 		continue
	# 	# print(item.split(' '))
	# 	main_content.append(getandsetter(item.split(' ')))

	main_content.append('}')

	# for item in main_content:
	# 	print(item)

	with open(package_name + '/' + java_name+'.java','w', encoding='utf-8') as f:
		f.writelines(main_content)				
		

		# print(package_name.replace('_','')) # 去掉_

	# 2.判断包名是否存在如果不存在，转3，否则转4
	# 3.创建包
	# 4.命名主Java文件，驼峰式命名，并创建java文件
	# 遍历json
	
		
	# os.makedirs(package_name)
	# for key in ret_dict['Model'].keys():.
	# 	print(key)
	# print(ret_dict['Model']['FBOOKID'])
	# print(type(ret_dict['Model']['FBOOKID']))
	# FCreateOrgId
	# print(type(ret_dict['Model']['FCreateOrgId']['FNumber']))

# 判断元素是否是Set,如果是Set,创建Java类
